"""Handles uri to model translations"""
from django.core.urlresolvers import RegexURLPattern, Resolver404
from django.utils.encoding import smart_str
from django.db.models import get_models
_model_uri_patterns = []

def resolve(model_uri):
    tried = []
    for model, pattern in _model_uri_patterns:
        try:
            match = pattern.resolve(model_uri)
        except Resolver404, e:
            tried.extend([(pattern.regex.pattern + '   ' + t) \
                              for t in e.args[0]['tried']])
        else:
            if match:
                callback, args, kwargs = match
                return callback(model, args, kwargs)

            tried.append(pattern.regex.pattern)
    raise Resolver404, {'tried': tried, 'path': model_uri}

def get_object(model, args, kwargs):
    return model.objects.get(**kwargs)

# Set the model uri patterns
for model in get_models():
    if hasattr(model, '__uri__'):
        _model_uri_patterns.append((model, RegexURLPattern(model.__uri__,
                                                   get_object)))

    
